package com.roy.netty.pojoTransfer;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.nio.charset.Charset;

/**
 * @author ：楼兰
 * @date ：Created in 2021/6/8
 * @description: 将POJO转码成为字节流
 **/

public class PojoEncoder extends MessageToByteEncoder<User> {
    @Override
    protected void encode(ChannelHandlerContext ctx, User msg, ByteBuf out) throws Exception {
        //按定长写字节流
        out.writeInt(msg.getUserId());
        out.writeDouble(msg.getUserSalary());
        //处理粘包问题的一种方法：写入username字符串的长度。
        final byte[] usernameBytes = msg.getUserName().getBytes("utf-8");
        out.writeInt(usernameBytes.length);
        //字符串长度不固定
        out.writeBytes(msg.getUserName().getBytes("utf-8"));


    }
}
